<?php
namespace app\index\controller;
use EasyWeChat\Message\Image;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use think\Cookie;
class Api extends Base
{你好吗亲爱的朋友
	/**
	 * 服务器在5秒内无法回复时的默认恢复的消息
	 */
	protected $replyContent = 'success';
	protected $opend_id      = null;
 	protected $beforeActionList = [
        'auth' =>  ['except'=>'getindex,postlogin,handler,event,text,getregister,postregister,postupload,getcreate,postsave']
    ];
    public function handler()
    {
    	// 从项目实例中得到服务端应用实例。
		$server = $this->app->server;
		$server->setMessageHandler(function ($message) {
		        switch ($message->MsgType) {
			        case 'event':
			            return $this->event($message);
			            break;
			        case 'text':
			            return $this->text($message->Content);
			            break;
			        default:
			            return $this->replyContent;
			            break;
			    }
		});
		$response = $server->serve();
		$response->send();
    }
	
	/**
	 * 接收事件时回复消息
	 * @param $event 事件类型
	 */
	public function event($message){
		switch ($message->Event) {
			case 'subscribe': 
					$this->replyContent = model('manager/BaseMsgs')->where(['id' => 1])->value('subscribe');
				break;
			case 'CLICK':
					$this->replyContent = $this->text($message->EventKey);
				break;
		}
		return $this->replyContent;
	}
	
	/**
	 * 接收文本时回复消息
	 * @param $content 消息内容
	 * @param 1=>回复文本消息； 2=>回复图文消息； 3=>回复图片消息
	 */
	public function text($content){
		$msg = model('manager/TextMsgs')->all();
		foreach ($msg as $v) {
			switch ( $v['type'] ) {
				case 1:
					if($v['keyword'] === $content){
						$this->replyContent = new Text(['content' => $v['content']]);
						break ;
					}
					break;
				case 2:
					if($v['keyword'] === $content){
						foreach ($v['content'] as &$v) {
							$v = new News($v);
						}
						$this->replyContent = $v['content'];
						break ;
					}
					break;
				case 3:
					if($v['keyword'] === $content){
						$this->replyContent = new Image(['media_id' => $v['content']]);
						break ;
					}
					break;
				default :
					$this->replyContent = '';
					break;	
			}
		}
		//匹配不到关键字，回复默认消息
		if( $this->replyContent == 'success' ){
			$this->replyContent = model('manager/BaseMsgs')->where(['id' => 1])->value('default');
		}
		return $this->replyContent;
	}
	
	/**
	 * 微信网页授权
	 */
	public function auth(){
		if(empty(Cookie::get('auth_id'))){
			$response = $this->app->oauth->scopes(['snsapi_base'])->redirect();		
			$response->send();
		}else{
			$this->app_id = Cookie::get('auth_id');
		}
	}
	
}
